package com.example.kekewaimaibao.deliver.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.kekewaimaibao.address.model.AddressDO;
import com.example.kekewaimaibao.core.constant.RestConstant;
import com.example.kekewaimaibao.deliver.model.DeliverDO;
import com.example.kekewaimaibao.deliver.service.IDeliverService;
import com.example.kekewaimaibao.order.model.OrderDO;
import com.example.kekewaimaibao.order.service.IOrderService;
import com.example.kekewaimaibao.rider.model.RiderDO;
import com.example.kekewaimaibao.shop.model.ShopDO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: xuxiang
 * @date: 2022/3/6 22:56 星期日
 * @description:
 * @version: 1.0
 */
@Slf4j
@RestController
@RequestMapping(DeliverController.PATH)
@Api(tags = "配送控制层")
@CrossOrigin
public class DeliverController {
    public static final String PATH = RestConstant.VERSION_V1 + "/deliver";

    @Autowired
    IDeliverService deliverService;

    @Autowired
    IOrderService orderService;

    /**
     * 建议弃用全表查询
     * @return
     */
    @ApiOperation(value = "所有配送列表")
    @GetMapping("/list")
    public R list() {
        List<DeliverDO> list = deliverService.list(null);
        return R.ok(list);
    }

    /**
     * 根据配送状态进行分页
     * @param current 当前页
     * @param limit 每页数据条数
     * @param deliverDO 配送信息
     * @return R
     */
    @ApiOperation(value = "分页查询配送信息")
    @PostMapping("/page/{current}/{limit}")
    public R page(@PathVariable long current, @PathVariable long limit,
                  @RequestBody(required = false) DeliverDO deliverDO) {
        Page<DeliverDO> page = new Page<>(current, limit);
        QueryWrapper<DeliverDO> wrapper = null;
        if (ObjectUtil.isNotNull(deliverDO)) {
            wrapper = new QueryWrapper<>();
            if (StrUtil.isNotBlank(deliverDO.getStatus())) {
                wrapper.eq("status", deliverDO.getStatus());
            }
        }
        deliverService.page(page, wrapper);
        long total = page.getTotal();
        List<DeliverDO> records = page.getRecords();
        Map map = new HashMap<>(4);
        map.put("current", current);
        map.put("limit", limit);
        map.put("total", total);
        map.put("records", records);
        return R.ok(map);
    }

    @ApiOperation(value = "添加配送信息")
    @PostMapping("/save")
    public R save(@RequestBody DeliverDO deliverDO) {
        boolean flag = deliverService.save(deliverDO);
        if (flag) {
            return R.ok("后台添加配送信息成功");
        } else {
            return R.failed("后台添加配送信息失败");
        }
    }

    @ApiOperation(value = "删除配送信息")
    @PostMapping("/remove/{id}")
    public R remove(@PathVariable Long id) {
        boolean flag = deliverService.removeById(id);
        if (flag) {
            return R.ok("后台删除id为" + id +"的配送信息成功");
        } else {
            return R.failed("后台删除配送信息失败");
        }
    }

    @ApiOperation(value = "更新配送信息")
    @PostMapping("update")
    public R update(@RequestBody DeliverDO deliverDO) {
        boolean flag = deliverService.updateById(deliverDO);
        if (flag) {
            return R.ok("后台更新id为" + deliverDO.getDeliverId() + "的配送信息成功");
        } else {
            return R.failed("后台更新配送信息失败");
        }
    }

    @ApiOperation(value = "批量删除配送信息")
    @PostMapping("/remove-ids/{ids}")
    public R deleteBatchIds(@PathVariable("ids")String[] ids) {
        List<String> list = Arrays.asList(ids);
        boolean flag = deliverService.removeByIds(list);
        if (flag) {
            return R.ok("批量删除配送信息成功");
        } else {
            return R.failed("批量删除配送信息失败");
        }
    }

    @ApiOperation(value = "通过id查找配送信息")
    @GetMapping("/get-by-id/{id}")
    public R getByShopId(@PathVariable Long id) {
        DeliverDO deliverDO = deliverService.getById(id);
        if (ObjectUtil.isNotNull(deliverDO)) {
            return R.ok(deliverDO);
        } else {
            return R.failed("未找到id为" + id + "的配送信息");
        }
    }

    /**
     * 商家端进行提交配送（所有骑手之后可通过待接单列表查看，选择配送单进行配送）
     * 1. 将订单信息提取出来封装到配送信息中
     * 2. 先更新订单信息的状态为配送中
     * 3. 当订单更新成功之后，新建配送信息（这个时候riderId为空，由骑手去接单更新）
     * @param orderDO
     * @return
     */
    @ApiOperation(value = "商家上传配送表")
    @PostMapping("/upload-deliver")
    public R uploadDeliverByShop(@RequestBody OrderDO orderDO) {
        Map<String, Object> map = JSON.parseObject(JSON.toJSONString(orderDO), Map.class);
        DeliverDO deliverDO = new DeliverDO();

        // 声明配送信息
        Long orderId = Long.parseLong(map.get("orderId").toString());
        Double sendCost = Double.parseDouble(map.get("sendCost").toString());
        String status = "0";
        String remark = map.get("remark").toString();

        // 将配送信息放入配送对象
        deliverDO.setOrderId(orderId);
        deliverDO.setSendCost(sendCost);
        deliverDO.setStatus(status);
        deliverDO.setRemark(remark);

        // 将订单状态改为配送中（这个之后也可以改成骑手端将订单状态修改为配送中，改不改都不影响业务）
        UpdateWrapper<OrderDO> wrapper = new UpdateWrapper<>();
        wrapper.eq("order_id", orderDO.getOrderId());
        wrapper.set("status", "3");
        boolean flag = orderService.update(wrapper);

        if (!flag) {
            R result = R.failed("订单信息更新失败");
            result.setCode(520);
            return result;
        }

        flag = deliverService.save(deliverDO);
        if (flag) {
            R result = new R();
            result.setMsg("上传配送成功");
            result.setCode(200);
            return result;
        } else {
            R result = R.failed("上传配送失败");
            result.setCode(520);
            return result;
        }
    }

    /**
     * 骑手端获取配送列表
     * 1. 如果待接单的话，所有骑手都能看到配送信息，否则只能看到该骑手接的配送信息
     * 2. 将用户地址信息，商家信息，配送信息封装到map里面传给前端，方便骑手端进行配送页面渲染
     * @param riderId 骑手ID
     * @param current 配送状态（status（0待接单 1待取货 2配送中 3已完成））
     * @return
     */
    @ApiOperation(value = "骑手获取配送列表")
    @GetMapping("/list-rider/{riderId}/{current}")
    public R listByRider(@PathVariable Long riderId, @PathVariable Long current) {
        QueryWrapper<DeliverDO> wrapper = new QueryWrapper<>();
        // 等于0的话，骑手都可以接单
        if (current != 0) {
            wrapper.eq("rider_id", riderId);
        }
        wrapper.eq("status", current);
        List<DeliverDO> deliverList = deliverService.list(wrapper);

        // 封装shopAddressList和userAddressList进入R.ok
        JSONArray shopAddressInfoArray = new JSONArray();
        JSONArray userAddressInfoArray = new JSONArray();
        for (DeliverDO deliverDO : deliverList) {
            JSONObject remarkJSON = JSON.parseObject(deliverDO.getRemark());
            // 做订单详情信息的容错，防止出现一个异常的订单详情，影响其他数据不可用
            if (ObjectUtil.isNull(remarkJSON)) {
                shopAddressInfoArray.add(null);
                userAddressInfoArray.add(null);
            }
            JSONObject shopAddressInfoJSON = remarkJSON.getJSONObject("shopAddressInfo");
            JSONObject userAddressInfoJSON = remarkJSON.getJSONObject("userAddressInfo");
            shopAddressInfoArray.add(shopAddressInfoJSON);
            userAddressInfoArray.add(userAddressInfoJSON);
        }

        Map<String, Object> map = new HashMap<>();
        map.put("deliverList", deliverList);
        map.put("shopAddressList", shopAddressInfoArray);
        map.put("userAddressList", userAddressInfoArray);

        R result = new R();
        result.setCode(200);
        result.setData(map);
        result.setMsg("获取配送列表信息成功");
        return result;
    }

    /**
     * 骑手更新配送单信息，根据当前配送状态选择不同方式进行更新
     * 1. 当前配送状态为待接单（0）时，更新配送状态为待取货（1），并将商家信息返回给骑手前端进行导航
     * 2. 当前配送状态为待取货（1）时，更新配送状态为配送中（2），并将用户地址信息返回给骑手前端进行导航
     * 3. 当前配送状态为配送中（2）时，更新配送状态为已完成（3）
     * 注：map中应该包含两个对象：配送对象deliverInfo和骑手对象riderInfo
     * @param map
     * @return
     */
    @ApiOperation(value = "骑手更新配送单")
    @PostMapping("/update-list")
    public R updateListByRider(@RequestBody Map<String, Object> map) {
        UpdateWrapper<DeliverDO> wrapper = new UpdateWrapper<>();

        // 获取配送对象和骑手对象
        String deliverInfo = JSON.toJSONString(map.get("deliverInfo"));
        String riderInfo = JSON.toJSONString(map.get("riderInfo"));
        DeliverDO deliverDO = JSON.parseObject(deliverInfo, DeliverDO.class);
        RiderDO riderDO = JSON.parseObject(riderInfo, RiderDO.class);

        // 判断配送状态字段是否正常
        if (StrUtil.isBlank(deliverDO.getStatus()) || !(deliverDO.getStatus().equals("0")
            || deliverDO.getStatus().equals("1")|| deliverDO.getStatus().equals("2")
                || deliverDO.getStatus().equals("3"))){
            R result = R.failed("数据库错误：配送状态字段不正常");
            result.setCode(520);
            return result;
        }
        // 判断骑手是否已经登录
        if (ObjectUtil.isNull(riderDO) || StrUtil.isBlank(riderDO.getRiderId().toString())) {
            R result = R.failed("骑手未登录");
            result.setCode(520);
            return result;
        }

        R result = new R();
        boolean flag = false;
        JSONObject remarkJSON = null;
        Map<String, Object> resultMap = new HashMap<>();
        String status = deliverDO.getStatus();
        switch (status) {
            // 骑手接单，前往商家取餐
            case "0":
                // 设置配送状态为待取货
                deliverDO.setStatus("1");
                // 更新配送信息
                wrapper.eq("deliver_id", deliverDO.getDeliverId());
                wrapper.set("status", deliverDO.getStatus());
                wrapper.set("rider_id", riderDO.getRiderId());
                flag = deliverService.update(wrapper);
                // TODO:判断是否更新成功
                // 从remark拿到商家信息
                remarkJSON = JSON.parseObject(deliverDO.getRemark());
                // TODO:remarkJSON是否为空的判断
                JSONObject shopAddressJSON = remarkJSON.getJSONObject("shopAddressInfo");
                ShopDO shopDO = JSON.parseObject(JSON.toJSONString(shopAddressJSON), ShopDO.class);
                // 将商家信息（前端主要是需要提取商家地址信息），方便骑手前往商家去取货
//                resultMap.put("shopAddressInfo", shopDO);
                result.setCode(200);
                result.setData(shopDO);
                result.setMsg("商家地址信息获取成功");
                return result;
//                break;
            case "1":
                // 设置配送状态为配送中
                deliverDO.setStatus("2");
                // 更新配送信息
                wrapper.eq("deliver_id", deliverDO.getDeliverId());
                wrapper.set("status", deliverDO.getStatus());
                flag = deliverService.update(wrapper);
                // TODO:判断是否更新成功
                // 从remark拿到用户信息
                remarkJSON = JSON.parseObject(deliverDO.getRemark());
                // TODO:判断remarkJSON是否为空
                JSONObject userAddressJSON = remarkJSON.getJSONObject("userAddressInfo");
                AddressDO addressDO = JSON.parseObject(JSON.toJSONString(userAddressJSON), AddressDO.class);
                // 将用户信息（前端主要是需要提取用户地址信息），方便骑手从商家赶往用户
//                resultMap.put("userAddressInfo", addressDO);
//                break;
                result.setCode(200);
                result.setData(addressDO);
                result.setMsg("用户地址信息获取成功");
                return result;
            case "2":
                // 设置配送状态为已完成
                deliverDO.setStatus("3");
                // 更新配送信息
                wrapper.eq("deliver_id", deliverDO.getDeliverId());
                wrapper.set("status", deliverDO.getStatus());
                flag = deliverService.update(wrapper);
                // TODO:判断是否更新成功
                // TODO：这个地方是否需要同步更新用户订单表的状态（暂时设置为不更改，由用户自行确认收货）
//                break;
                result.setCode(200);
                result.setMsg("配送已完成，您辛苦了");
                return result;
            default:
                // 配送状态已经为已完成了
                result.setCode(200);
                result.setMsg("配送单已完成，无需修改");
                return result;
        }
    }

    /**
     * 通过骑手ID统计骑手已完成状态的配送数据
     * dayMap中有dayCount（今日完成配送量），dayMoney（今日配送费）
     * monthMap中有monthCount（本月完成配送量），monthMoney（本月配送费）
     * yearMap中有yearCount（今年完成配送量），yearMoney（今年配送费）
     * @param riderId 骑手ID
     * @return
     */
    @ApiOperation(value = "骑手数据看板")
    @GetMapping("/dashboard/{riderId}")
    public R getDashBoardData (@PathVariable Long riderId) {
        Map<String, Object> dayMap = deliverService.getDayDashBoard(riderId);
        Map<String, Object> monthMap = deliverService.getMonthDashBoard(riderId);
        Map<String, Object> yearMap = deliverService.getYearDashBoard(riderId);
        Map<String, Object> map = new HashMap<>();
        map.put("dayMap", dayMap);
        map.put("monthMap", monthMap);
        map.put("yearMap", yearMap);
        R result = new R();
        result.setCode(200);
        result.setData(map);
        return result;
    }
}
